<?php

namespace app\wechat\controller;

use app\common\model\BarragerModel;
use app\common\model\ConfigModel;

/**
 * Class Barrager
 * @package app\wechat\controller
 */
class Barrager extends \think\Controller
{
    public function index()
    {
        return $this->fail("hello world!");
    }

    /**
     * 新增弹幕
     *
     * @return \think\response\Json
     * @throws \think\Exception
     */
    public function add()
    {
        $arr = $this->ioAll();
        $arr['state'] = 1;
        $barragerModel = new BarragerModel();
        if ($barragerModel->where(["openId" => $arr['openId']])->count() >= 3 && $arr['openId'] != "oVxJd5bVXUqbP6gc0qVUQr2T_Vlk") {
            return $this->fail();
        } else {
            $barragerSave = $barragerModel->save($arr);
            return $barragerSave ? $this->ok($barragerSave) : $this->fail("新增弹幕失败");
        }
    }

    /**
     * 修改弹幕状态
     *
     * @return \think\response\Json
     */
    public function update()
    {
        $arr = $this->ioAll();
        $barragerModel = new BarragerModel();
        $barragerSave = $barragerModel->updateEx($arr);
        return $barragerSave ? $this->ok($barragerSave) : $this->fail("修改弹幕状态失败");
    }

    /**
     * 大屏获取弹幕
     *
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function show()
    {
        $configModel = new ConfigModel();
        $configData = $configModel->find();
        if ($configData->barrager) {
            $barragerModel = new BarragerModel();
            $rows = M('BarragerModel')
                ->alias('barrager')
                ->join('user_info userInfo', 'barrager.openId=userInfo.openId')
                ->where('barrager.state', 2)
                ->field(['barrager.id', 'barrager.style', 'barrager.note', 'userInfo.avatarUrl'])
                ->select();
            foreach ($rows as $item) {
                $barragerModel->updateEx(["id" => $item['id'], "state" => 3]);
            }
        } else {
            $rows = [];
        }
        return $this->ok($rows);
    }

    /**
     * 管理员获取弹幕
     *
     * @return \think\response\Json
     */
    public function admin()
    {
        $rows = M('BarragerModel')
            ->alias('barrager')
            ->join('user_info userInfo', 'barrager.openId=userInfo.openId')
            ->where('barrager.state', 1)
            ->field(['barrager.*', 'userInfo.nickName', 'userInfo.avatarUrl'])
            ->select();
        return $this->ok($rows);
    }
}
